package com.lagou.worker.config;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RegisterFilter
 * @Description 全局限定规定时间内对应IP最大的注册次数
 * @Author xsq
 * @Date 2020/7/17 14:51
 **/
@Slf4j
@Component // 让容器扫描到，等同于注册了
public class RegisterFilter implements GlobalFilter, Ordered {

    private Map<String, Integer> map = new ConcurrentHashMap<>();

    @Value("${gateway.register.max.number}")
    private Integer registerMaxNumber;

    @Value("${gateway.register.time}")
    private Integer registerTime;


    private Cache<String, Integer> cache;

    @PostConstruct
    public void init() {
        log.info("初始化cache对象：time:{}", registerTime);
        cache = CacheBuilder.newBuilder().expireAfterAccess(registerTime, TimeUnit.MINUTES).build();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        String clientIp = request.getRemoteAddress().getHostString();
        if (path.contains("/register")) {
            log.info("request ip:{}; path:{}", clientIp, path);
            log.info("gateway.register.max.number:{}", registerMaxNumber);

            Integer requestSize = cache.getIfPresent(clientIp);
            if (requestSize == null) {
                requestSize = 0;
            }
            requestSize++;
            cache.put(clientIp, requestSize);
            log.info("url [{}] {}分钟的请求次数为{}", path, registerTime, requestSize);
            if (requestSize > registerMaxNumber) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====>IP:{}，已超过请求次数，将被拒绝访问！", clientIp);
                String data = "=====>IP:{" + clientIp + "}，已超过请求次数，目前请求次数为" + requestSize + "次将被拒绝访问！";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
